package com.example.tiantian.battery;

import com.example.tiantian.R;
import android.annotation.SuppressLint;
import android.app.TabActivity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabWidget;
import android.widget.TextView;

@SuppressLint("InflateParams")
@SuppressWarnings("deprecation")
public class BatteryActivity extends TabActivity implements OnTabChangeListener {

    TabHost host;
    TabWidget tabs;
    LayoutInflater inflater;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

        init();
        loadData();
        event();
    }

    protected void init() {
        setContentView(R.layout.activity_tab);

        host = (TabHost) findViewById(android.R.id.tabhost);
        tabs = host.getTabWidget();
        inflater = LayoutInflater.from(this);
    }

    protected void loadData() {
        addTab("charge");
        addTab("info");
        changeTabBg(0);
    }

    protected void event() {
        host.setOnTabChangedListener(this);
    }

    private void addTab(String tabName) {
        View tab = inflater.inflate(R.layout.tab_label, null);
        TextView txt = (TextView) tab.findViewById(R.id.tab_txt);
        txt.setText(tabName.equals("info") ? R.string.battery_info : R.string.battery_charge);
        Drawable image = getResources().getDrawable(
                tabName.equals("info") ? R.drawable.battery_tab_info_selected : R.drawable.battery_tab_tain_selected);
        image.setBounds(0, 0, image.getMinimumWidth(), image.getMinimumHeight());
        txt.setCompoundDrawables(null, image, null, null);
        txt.setCompoundDrawablePadding(5);

        TabHost.TabSpec spec = host.newTabSpec(tabName);
        spec.setIndicator(tab);

        Intent intent = new Intent(this,
                tabName.equals("info") ? BatteryInfoActivity.class : BatteryChargeActivity.class);
        spec.setContent(intent);

        host.addTab(spec);
    }

    public void changeTabBg(int tabindex) {
        for (int i = 0; i < tabs.getChildCount(); i++) {
            View v = tabs.getChildAt(i);
            if (i == tabindex) {
                // 将当前循环到的v设置成被选择模式
                v.setBackgroundResource(R.drawable.img_backgra);
            } else {
                v.setBackgroundResource(R.drawable.backimg_fouce);
            }
        }
    }

    @Override
    public void onTabChanged(String tabId) {
        changeTabBg(host.getCurrentTab());
    }
}
